#include "BattleMap.h"
#include "Soldier.h"
#include <time.h>

BattleMap::BattleMap( unsigned int row, unsigned int column )
: m_cMapRow(row)
, m_cMapColumn(column)
{
	m_piMap = new unsigned int[m_cMapRow * m_cMapColumn];

	for(unsigned int i = 0; i < m_cMapRow * m_cMapColumn; ++i)
	{
		m_piMap[i] = 0;
	}

	srand((unsigned int)time(NULL));
}

BattleMap::~BattleMap()
{
	delete[] m_piMap;
	m_piMap = 0;
}

bool BattleMap::AddSoldierToMap( Soldier* pSoldier )
{
	unsigned int randColumn = rand() % m_cMapColumn;
	unsigned int tempColumn = randColumn;

	do
	{
		if(InsertSoldierToColumn(pSoldier, tempColumn))
		{
			return true;
		}

		if(tempColumn > (unsigned int)(m_cMapColumn - pSoldier->GetWidth()))
		{
			tempColumn = 0;
		}
		else
		{
			++tempColumn;
		}
	}
	while(tempColumn != randColumn);

	return false;
}

void BattleMap::RemoveSoldierFromMap( Soldier* pSoldier )
{

}

unsigned int BattleMap::GetMapRow()
{
	return m_cMapRow;
}

unsigned int BattleMap::GetMapColumn()
{
	return m_cMapColumn;
}

bool BattleMap::InsertSoldierToColumn( Soldier* pSoldier, unsigned int column )
{
	int columnend = GetEndOfColumn(column);
	if(m_cMapRow - columnend - 1 < pSoldier->GetHight())
	{
		return false;
	}

	for(unsigned char i = 0; i < pSoldier->GetWidth(); ++i)
	{
		if(m_piMap[(columnend + 1) * m_cMapColumn + column + i] != 0)
		{
			return false;
		}
	}

	InsertSoldierToMap(pSoldier, columnend + 1, column);
	return true;
}

void BattleMap::InsertSoldierToMap( Soldier* pSoldier, unsigned int row, unsigned int column )
{
	unsigned int* tempmap = new unsigned int[pSoldier->GetHight() * pSoldier->GetWidth()];
	for(unsigned char hight = 0; hight < pSoldier->GetHight(); ++hight)
	{
		for(unsigned char width = 0; width < pSoldier->GetWidth(); ++width)
		{
			m_piMap[(row + hight) * m_cMapColumn + column + width] = pSoldier->GetID();
			tempmap[hight * pSoldier->GetWidth() + width] = (row + hight) * m_cMapColumn + column + width;
		}
	}

	pSoldier->SetOwnMap(tempmap);
	m_SoldierContainer.AddSoldier(pSoldier);
}


int BattleMap::GetEndOfColumn( unsigned int column )
{
	if(column >= m_cMapColumn)
	{
		return m_cMapRow;
	}

	for(unsigned int i = 0; i < m_cMapRow; ++i)
	{
		if(m_piMap[i * m_cMapColumn + column] == 0)
		{
			return i - 1;
		}
	}

	return m_cMapRow - 1;
}
